import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, Input, Popconfirm, Row, DatePicker, Table, message} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import FreightFeeDetail from '../../components/fee/freightFee/freightFeeDetail';
import ImportFile from '../../components/common/importFile';
import PortSelect from '../../components/common/portSelect';
import { download } from '../../utils/commons';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const R = require("ramda");

const freightFee = Form.create()(class FreightFee extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            rate: [],
            rateKeys: []
        }
    }

    componentDidMount() {
        this.props.dispatch({ type: 'freightFee/getListForPage', payload: { page: Constants.DEFAULT_PAGE } });
    }

    handleOpen = (id, disabled) => {
        this.props.dispatch({
            type: 'freightFee/getFreightFeeById',
            payload: {
                id,
                onSuccess: () => {
                   let airlineId = this.props.freightFee.dataSource && this.props.freightFee.dataSource.airlineId ? this.props.freightFee.dataSource.airlineId : null;
                   if(!R.isNil(airlineId)){
                       this.props.dispatch({
                           type: "airline/getAirlineIdPorts",
                           payload: {
                               airlineId: airlineId,
                               onSuccess: () => {}
                           }
                       })
                   }
                }
            }
        });

        this.props.dispatch({ type: 'supplier/getSupplierList', payload: {  supplierType: Constants.SUPPLIER_TYPE.FRAE } });  //查询海运供应商
        this.props.dispatch({ type: 'airline/getAllAirLines' });   //查询航线
        this.props.dispatch({ type: 'berthingCompany/getAllBerthingCompanys' }); //查询船公司


        this.freightFeeDetail.handleOpen(disabled);
    }

    handleImport = (module) =>{
        this.importFile.handleOpen(module);
    }

    handleExport = () => {
        if (!this.state.rate || this.state.rate.length === 0) {
            message.error("请先选择要导出的海运费"); return;
        }

        let values = this.props.form.getFieldsValue();
        let feeIds = this.state.rateKeys;
        let url = apiPath.mc + "/api/freight/generate";
        download(url, {feeIds});
    }

    cleanSelected = () => {
        this.setState({ rateKeys: [], rate: [] });
    }

    handleDelete = id => {
        this.props.dispatch({
            type: 'freightFee/deleteById',
            payload: {
                id,
                onSuccess: this.handleSearch
            }
        })
    }

    handleSearch = flag => {
        let values = this.props.form.getFieldsValue();
        values.beginTime = R.isNil(values.effectiveTime) || R.isEmpty(values.effectiveTime) ? null : values.effectiveTime[0].format(Constants.DATEFORMAT);
        values.endTime = R.isNil(values.effectiveTime) || R.isEmpty(values.effectiveTime) ? null : values.effectiveTime[1].format(Constants.DATEFORMAT);
        let newPage = this.props.freightFee.page;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'freightFee/getListForPage',
            payload: {
                type: Constants.TYPE1,
                ...values,
                page: newPage
            }
        });
    };

    columns = [
        { title: '供应商名称/代码', width: '220px',
            render: record =>{
                return <span>{record.companyname}({record.supplierCode})</span>
            }    
        },
        { title: '航线名称', dataIndex: 'airlineName', key: 'airlineName  ' },
        { title: '船公司代码', dataIndex: 'berthingCode', key: 'berthingCode' },
        { title: '起运港',
            render: record =>{
                return <span>
                    <div>{record.loadingEnName}</div>
                    <div>({record.loadingName})</div>
                </span>
            }
        },
        { title: '目的港',
            render: record =>{
                return <span>
                    <div>{record.destinationEnName}</div>
                    <div>({record.destinationName})</div>
                </span>
            }
        },
        { title: '航程(天数)', dataIndex: 'sail', key: 'sail' },
        { title: '船期', dataIndex: 'cut_off', key: 'cut_off'},
        { title: '是否中转', render(record) {
            if(record.transit === '1'){
                return '是';
            }else if(record.transit === '2'){
                return '否';
            }else{
                return '未知';
            }
        }},
        { title: '中转港',
            render: record =>{
                let transitName = record.transitName ? "(" + record.transitName + ")" : undefined
                return <span>
                    <div>{record.transitEnName}</div>
                    <div>{transitName}</div>
                </span>
            }
        },
        { title: '20GP', dataIndex: 'fee20gp', key: 'fee20gp' },
        { title: '40GP', dataIndex: 'fee40gp', key: 'fee40gp  ' },
        { title: '40HQ', dataIndex: 'fee40hq', key: 'fee40hq' },
        //{ title: '备注', dataIndex: 'memo', key: 'memo' },
        { title: '开始时间', dataIndex: 'begindate', key: 'begindate' },
        { title: '截止时间', dataIndex: 'enddate', key: 'enddate' },
        { title: '创建时间', dataIndex:'createtime', key: 'createtime'},
        {
            title: '操作',
            render: (record) => {
                let editLink = <RightBox resource={RightConstants.COSTMAINTENANCE.COSTMAINTENANCE_FREIGHTFEE_EDIT} split={true}><a href="#" onClick={this.handleOpen.bind(this, record.id, false)}>编辑</a></RightBox>
                let deleteLink = <Popconfirm onConfirm={this.handleDelete.bind(this, record.id)} okText="是" cancelText="否"
                    placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除?'}>
                    <a href="#">删除</a>
                </Popconfirm>
                deleteLink = <RightBox resource={RightConstants.COSTMAINTENANCE.COSTMAINTENANCE_FREIGHTFEE_DELETE} split={true}>{deleteLink}</RightBox>
                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true)}>查看</a>
                return <span>{editLink}{deleteLink}{viewLink}</span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.freightFee.page.size,
            current: this.props.freightFee.page.page,
            total: this.props.freightFee.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.freightFee.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'freightFee/getListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.freightFee.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'freightFee/getListForPage',
                    payload: {
                        ...this.props.form.getFieldsValue(),
                        page: newPage
                    }
                });
            }
        }

        let rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    rateKeys: selectedRowKeys
                })
            },
            onSelect: (record, selected, selectedRows, nativeEvent) => {
                let rate = [...this.state.rate];
                if (selected) rate.push(record)
                else rate = R.difference(rate, [record]);
                this.setState({ rate });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                let rate = [...this.state.rate];
                if (selected) rate = rate.concat(changeRows);
                else rate = R.difference(rate, changeRows);
                this.setState({ rate });
            },
            selectedRowKeys: this.state.rateKeys
        };

        return (
            <div>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'供应商'}>
                            {getFieldDecorator('supplier')
                                (
                                <Input maxLength="20" placeholder="可根据供应商代码、中英文名称搜索" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'航线'}>
                            {getFieldDecorator('airline')
                                (
                                <Input  maxLength="200" placeholder="可根据航线代码、名称搜索" />
                                )
                            }
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'船公司'}>
                            {getFieldDecorator('berthing')
                                (
                                <Input maxLength="200" placeholder="可根据船公司代码、中英文名称搜索" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'有效期'}>
                            {getFieldDecorator('effectiveTime')(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '截止时间']}
                                />
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'起运港'}>
                            {getFieldDecorator('loadingPort')(
                                <PortSelect style={{ width: '100%' }} portType={"1"} allowClear />
                            )}
                        </FormItem>

                    </Col>
                    <Col span={6}>
                        <FormItem {...formItemLayout} label={'目的港'}>
                            {getFieldDecorator('destinationPort')(
                                <PortSelect style={{ width: '100%' }} portType={"1"} allowClear />
                            )}
                        </FormItem>
                    </Col>
                    <Col span={11} style={{ marginLeft: 24}}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)} size={'default'}>查询</Button>
                        <RightBox resource={RightConstants.COSTMAINTENANCE.COSTMAINTENANCE_FREIGHTFEE_ADD}>
                            <Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleOpen.bind(this, null, false)} size={'default'}>新增海运费</Button>
                        </RightBox>
                        <RightBox resource={RightConstants.COSTMAINTENANCE.COSTMAINTENANCE_FREIGHTFEE_IMPORT}>
                            <Button type="primary" icon="plus" style={{ marginRight: 5 }} onClick={this.handleImport.bind(this, Constants.IMPORT_MODULE[7])} size={'default'}>导入海运费</Button>
                        </RightBox>
                        <RightBox resource={RightConstants.COSTMAINTENANCE.COSTMAINTENANCE_FREIGHTFEE_EXPORT}>
                            <Button type="primary" icon="export" style={{ marginRight: 5 }} onClick={this.handleExport.bind(this)} size={'default'}>导出海运费</Button>
                        </RightBox>
                    </Col>
                </Row>

                <Table title={() => <span>已选择
                         <a style={{ fontWeight: 600, marginLeft: 5 }}>{this.state.rateKeys.length}</a> 项
                         <a onClick={this.cleanSelected.bind(this)} style={{ marginLeft: 10 }}>清空</a></span>
                        }
                        loading={this.props.loading} rowKey='id' 
                        dataSource={this.props.freightFee.list} 
                        columns={this.columns} bordered={true} 
                        size={'middle'} pagination={pagination} 
                        rowSelection={rowSelection}
                />
                <FreightFeeDetail wrappedComponentRef={(inst) => this.freightFeeDetail = inst} refreshList={this.handleSearch} />
                <ImportFile wrappedComponentRef={(inst) => this.importFile = inst} refreshList={this.handleSearch} />
            </div>
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.freightFee, freightFee: state.freightFee
    };
}

export default connect(mapStateToProps)(freightFee);
